<template>
  <div class="user-manage">
    <!-- 弹出对话框 -->
    <el-dialog title="提示" :visible.sync="dialogVisible" :before-close="handleClose" width="50%">
      <el-form ref="form" :rules="rules" :inline="true" :model="form" label-width="80px">
        <el-form-item label="用户id" prop="userId">
          <el-input placeholder="请输入姓名" v-model="form.userId"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="userName">
          <el-input placeholder="请输入姓名" v-model="form.userName"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input placeholder="请输入昵称" v-model="form.nickName"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input placeholder="请输入电话" v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input placeholder="请输入地址" v-model="form.address"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 顶部操作栏 -->
    <div class="manage-header" style="margin-bottom: 10px;">
      <el-button @click="handleAdd()" type="primary" size="small">+ 新增</el-button>
      <el-button @click="getUserList()" type="primary" size="small">获取用户列表</el-button>
      <el-button @click="exportUserList()" type="primary" size="small">导出用户列表</el-button>
      <el-upload name="file" action="1" :http-request="importUser" style="display: inline-block; margin-left: 10px;">
        <el-button size="small" type="primary" :loading="loadingUpload">导入用户</el-button>
      </el-upload>
      <div style="display: block;">
        <span class="search-font">用户id:</span>
        <el-input v-model="userId" placeholder="请输入用户id" style="width: 200px; margin: 20px;" size="small" clearable @keyup.enter.native="handleEnter"/>
        <span class="search-font">姓名:</span>
        <el-input v-model="userName" placeholder="请输入姓名" style="width: 200px; margin: 20px;" size="small" clearable @keyup.enter.native="handleEnter"/>
        <span class="search-font">昵称:</span>
        <el-input v-model="nickName" placeholder="请输入昵称" style="width: 200px; margin: 20px;" size="small" clearable @keyup.enter.native="handleEnter"/>
        <span class="search-font">地址:</span>
        <el-input v-model="address" placeholder="请输入地址" style="width: 200px; margin: 20px;" size="small" clearable @keyup.enter.native="handleEnter"/>
        <el-button @click="clearInputs()" type="primary" size="small">清除内容</el-button>
        <el-button @click="searchUser()" type="primary" size="small">搜索</el-button>
      </div>
    </div>

    <!-- 表格容器 -->
    <div class="table-container">
      <el-table :data="tableData" style="width: 100%" :max-height="600">
        <el-table-column prop="userId" label="用户id" width="180"></el-table-column>
        <el-table-column prop="userName" label="姓名" width="180"></el-table-column>
        <el-table-column prop="nickName" label="昵称" width="180"></el-table-column>
        <el-table-column prop="phone" label="电话" width="180"></el-table-column>
        <el-table-column prop="address" label="地址"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="handleUpdate(scope.row)" size="small">修改</el-button>
            <el-button @click="deleteUser(scope.row.userId)" type="danger" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页条 固定在底部 -->
    <div class="pagination-container"
         style="position: fixed; bottom: 0; width: 100%; background-color: #fff; padding: 10px; box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.1);">
      <el-pagination
          background
          layout="total, sizes, prev, pager, next"
          :total="totalCount"
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[5, 10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import requestUtil from '../network/request'

export default {
  /*单个单词命名，template会报错，但其实不影响*/
  name: 'userPage',
  data() {
    return {
      dialogVisible: false,
      form: {
        userId: '',
        userName: '',
        password: '',
        nickName: '',
        phone: '',
        address: ''
      },
      rules: {
        userId: [
          {required: true, message: '请输入用户id'},
          {min: 1, max: 30, message: '长度在 1 到 30 个字符'}
        ],
        userName: [
          {required: true, message: '请输入姓名'},
          {min: 1, max: 30, message: '长度在 1 到 30 个字符'}
        ],
        password: [
          {required: true, message: '请输入密码'}
        ]
      },
      tableData: [],
      opType: 'add', // add-新增 update-修改
      currentPage: 1, // 当前页
      pageSize: 10, // 页大小
      totalPage: 1,
      totalCount: 0,
      userId: '',
      userName: '',
      nickName: '',
      address: '',
      tableMaxHeight: 400, // 设置表格最大高度
      loadingUpload: false
    };
  },
  watch: {
    // 监听搜索条件的变化
    userId(val) { this.resetPageOnSearchChange(val); },
    userName(val) { this.resetPageOnSearchChange(val); },
    nickName(val) { this.resetPageOnSearchChange(val); },
    address(val) { this.resetPageOnSearchChange(val); }
  },
  methods: {
    async importUser(e) {
      // 检查文件扩展名
      let names = e.file.name.split('.')
      let isXls = names[names.length - 1] === 'xls'
      let isXlsx = names[names.length - 1] === 'xlsx'

      // 检查文件大小
      let fileSize = (e.file.size / 1024 / 1024) < 3

      if (!isXls && !isXlsx) {
        this.$message.error('上传模板只能是 xls 或 xlsx 格式！')
        return false
      }
      if (!fileSize) {
        this.$message.error('上传模板大小不能超过 3MB！')
        return false
      }
      try {
        this.loadingUpload = true
        let fileData = new FormData()
        fileData.append('file', e.file)
        const data = await requestUtil.upload('/file/upload', fileData)
        if (data.code === '0') {
          this.$message({ message: '上传成功', type: 'success' })
        }
        this.loadingUpload = false
      } catch(err) {
        this.loadingUpload = false
      }
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if ('add' === this.opType) {
            // 后续对表单数据的处理
            requestUtil.post('/user/add', this.form).then(res => {
              if (res.code === '0') {
                this.$message({
                  message: "新增成功",
                  type: 'success'
                })
                this.getUserList()
              } else {
                this.$message.error(res.msg)
              }
            })
          } else if ('update' === this.opType) {
            requestUtil.post('/user/update', this.form).then(res => {
              if (res.code === '0') {
                this.$message({
                  message: "更新成功",
                  type: 'success'
                })
                this.getUserList()
              } else {
                this.$message.error(res.msg)
              }
            })
          }
          this.handleClose()
        }
      })
    },
    cancel() {
      this.handleClose()
    },
    handleClose() {
      this.dialogVisible = false;
      this.$refs.form.resetFields()
    },
    handleAdd() {
      this.opType = 'add'
      this.dialogVisible = true
    },
    handleUpdate(row) {
      this.opType = 'update'
      this.dialogVisible = true
      // 注意这里需要对数据进行深拷贝，否则会出错 （有点类似java里的地址传递）
      this.form = JSON.parse(JSON.stringify(row))
    },
    handleEnter(event) {
      event.preventDefault();
      this.searchUser();
    },
    resetPageOnSearchChange(newValue) {
      if (newValue !== undefined && newValue !== null) {
        // 如果有任意一个搜索条件发生了变化，则重置到第一页
        this.currentPage = 1;
      }
    },
    clearInputs() {
      this.userId = ''
      this.userName = ''
      this.nickName = ''
      this.address = ''
    },
    searchUser() {
      requestUtil.post('/user/info/list', {
        page: {
          currentPage: this.currentPage,
          pageSize: this.pageSize
        },
        userId: this.userId,
        userName: this.userName,
        nickName: this.nickName,
        address: this.address
      }).then(res => {
        this.tableData = res.result.userInfoList
        this.totalCount = res.page ? res.page.totalCount : 0
      })
    },
    getUserList() {
      requestUtil.post('/user/info/list', {
        page: {
          currentPage: this.currentPage,
          pageSize: this.pageSize
        }
      }).then(res => {
        this.tableData = res.result.userInfoList
        this.totalCount = res.page ? res.page.totalCount : 0
      })
    },
    deleteUser(userId) {
      requestUtil.post('/user/del', {
        "userId": userId
      }).then(res => {
        if (res.code === '0') {
          this.$message({
            message: "删除成功",
            type: 'success'
          })
          this.getUserList()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    exportUserList() {
      requestUtil.post('/user/list/export', {
        userId: this.userId,
        userName: this.userName,
        nickName: this.nickName,
        address: this.address
      }).then(res => {
        if (res.code === '0') {
          this.$message({
            message: "操作成功",
            type: 'success'
          })
          //this.getUserList()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handlePageChange(currentPage) {
      this.currentPage = currentPage
      this.getUserList()
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.getUserList(); // 更新页大小后重新获取数据
    },
  },
  mounted() {
    this.getUserList()
  }
};
</script>

<style lang="less" scoped>
/deep/ .el-upload-list{
  display: none;
}
.user-manage {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.manage-header {
  flex: 0 0 auto;
}

.table-container {
  flex: 1 1 auto;
  padding: 10px;
  box-sizing: border-box;
}

.pagination-container {
  flex: 0 0 auto;
  padding: 10px;
  box-sizing: border-box;
}

.search-font {
  color: #909399;
  font-size: 14px;
  font-weight: bold;
}
</style>